<template>
  <Form :model="formData">

    <Row :gutter="32">
      <Col span="12">
        <FormItem label="用户名" label-position="top">
          <Input v-model="formData.username" placeholder="请输入用户名" :readonly="row.id!=null" />
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="初始默认密码" label-position="top">
          <Input v-model="formData.password" placeholder="密码如果为空，则不会修改密码"/>
        </FormItem>
      </Col>
    </Row>

    <Row :gutter="32">
      <Col span="12">
        <FormItem label="真实姓名" label-position="top">
          <Input v-model="formData.realName" placeholder="请输入真实姓名"/>
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="手机号" label-position="top">
          <Input v-model="formData.tel" placeholder="请输入手机号"/>
        </FormItem>
      </Col>
    </Row>

    <Row :gutter="32">
      <Col span="12">
        <FormItem label="部门" label-position="top">
          <Select v-model="formData.departs" multiple placeholder="请选择部门">
            <Option v-for="item in departList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="岗位" label-position="top">
          <Select v-model="formData.positions" multiple placeholder="请选择岗位">
            <Option v-for="item in positionList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
      </Col>
    </Row>


    <Row :gutter="32">
      <Col span="12">
        <FormItem label="出生日期" label-position="top">
          <DatePicker type="date" v-model="formData.birth"
                      placeholder="请选择出生日期" :options="options"/>
        </FormItem>
      </Col>
      <Col span="12">
        <FormItem label="电子邮箱" label-position="top">
          <Input v-model="formData.email" placeholder="请输入电子邮箱" style="width:260px"/>
        </FormItem>
      </Col>
    </Row>

    <div>
      是否锁定用户
      <Tooltip content="锁定用户后,该用户不能登录系统">
        <Icon type="ios-help-circle" size="20"/>
      </Tooltip>
    </div>
    <Switch v-model="formData.locked">
      <template #open>
        <Icon type="md-checkmark"></Icon>
      </template>
      <template #close>
        <Icon type="md-close"></Icon>
      </template>
    </Switch>
  </Form>

  <div class="demo-drawer-footer">
    <Button style="margin-right: 8px" @click="$emit('close-win', false)">关闭</Button>
    <Button type="primary" @click="saveOrUpdateUser">保存</Button>
  </div>
</template>

<script>
export default {
  props: {
    row: {
      type: Object,
      required: false,
      default: {}
    }
  },
  data() {
    return {
      formData: {
        username: this.row.username,
        password: this.row.id != null ? '' : '123456',
        birth: '',
        realName: this.row.realName,
        tel: this.row.tel,
        positions: [],
        departs: [],
        email: this.row.email,
        locked: this.row.locked,
      },
      departList: [],
      positionList: [],
      options: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        }
      },
    }
  },
  created() {
    // 查询所有的角色 和 当前用户挂载的角色
    this.queryDeparts();
    this.queryPositions() ;
  },
  emits: ["close-win"],
  mounted() {
    if (this.row.birth != null) {  // 挂载页面后，将传入的日期进行更新显示
      // 拆分 字符串
      let array = this.row.birth.split("-");
      this.formData.birth = new Date(...array);
    }
  },
  methods: {
    queryDeparts() {
      this.$api.queryAllDepartsByUserId(this.row.id).then(({data: ret}) => {
        if (ret.status === "10000") {
          this.departList = ret.data.map(r => ({value: r.id, label: r.name}));
          if (this.row.id!=null) this.formData.departs = ret.data.filter(r => r.checked).map((r => r.id));
        }
      })
    },
    queryPositions() {
      this.$api.queryAllPositionsByUserId(this.row.id).then(({data: ret}) => {
        if (ret.status === "10000") {
          this.positionList = ret.data.map(r => ({value: r.id, label: r.name}));
          if (this.row.id != null) {
            this.formData.positions = ret.data.filter(r => r.checked).map((r => r.id));
          }
        }
      })
    },
    formatDate(date) {
      if (date === "") return null ;
      let year = date.getFullYear();
      let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1 ;
      let day =date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      return `${year}-${month}-${day}`
    },
    saveOrUpdateUser() {
      // 验证数据
      if (this.formData.username == null || this.formData.username === "") {
        this.$Message.error({background: true, content: "用户名为空"});
        return false;
      }

      if (this.row.id == null && (this.formData.password == null || this.formData.password === "")) {
        this.$Message.error({background: true, content: "密码不允许为空"});
        return false;
      }

      if (this.formData.realName == null || this.formData.realName === "") {
        this.$Message.error({background: true, content: "真实姓名为空"});
        return false;
      }

      if (this.formData.tel == null || this.formData.tel === "") {
        this.$Message.error({background: true, content: "手机号为空"});
        return false;
      }

      if (!/^1[3-9]\d{9}$/.test(this.formData.tel)) {
        this.$Message.error({background: true, content: "手机号格式不正确"});
        return false;
      }

      if (this.formData.birth == null || this.formData.birth === "") {
        this.$Message.error({background: true, content: "出生日期为空"});
        return false;
      }

      if (this.formData.email == null || this.formData.email === "") {
        this.$Message.error({background: true, content: "电子邮箱为空"});
        return false;
      }

      let birth = this.formatDate(this.formData.birth);

      if (this.row.id == null)  {
         // 保存数据
         this.$api.saveUser({...this.formData, birth: birth}).then(({data:ret})=> {
            if (ret.status === "10000") {
              this.$Message.success({background: true, content: "数据保存成功"});
              this.$emit('close-win', true) ;
            }else{
              this.$Message.error({background: true, content: ret.message});
            }
         })
      }else{
         // 更新数据
         this.$api.modifyUser(this.row.id, {...this.formData, birth: birth}).then(({data:ret})=> {
           if (ret.status === "10000") {
             this.$Message.success({background: true, content: "数据修改成功"});
             this.$emit('close-win', true) ;
           }else{
             this.$Message.error({background: true, content: ret.message});
           }
         })
      }
    }
  }
}
</script>

<style scoped>
.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
</style>